import cv2
import numpy as np
img = cv2.imread('Bright1.jpg') #临时代替摄像头捕捉画面

# cap = cv2.VideoCapture(0) #使用默认摄像头
#读取图像识别
if img is None:
    print("读取图像失败")
    exit()
#灰度化
gray_image = cv2.cvtColor(img,cv2.COLOR_BGRA2GRAY)
#高斯模糊
blurred_image =cv2.GaussianBlur(gray_image,(15,15),0)
#自适应
thresh_image = cv2.adaptiveThreshold(blurred_image,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY_INV,15,2)
# 寻找亮源
contours,_ = cv2.findContours(thresh_image,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
# 遍历轮廓
for contour in contours:
    #计算轮廓边框
    x,y,w,h = cv2.boundingRect(contour)
    #计算轮廓面积
    area = cv2.contourArea(contour)
    #如果面积大于一定值，判断是否为亮源
    if area >200: #阈值
        #计算轮廓的中心点
        M = cv2.moments(contour)
        if M["m00"] != 0:
            cX = int(M["m10"] / M["m00"])
            cY = int(M["m01"] / M["m00"])
        else:
            cX, cY = x + w // 2, y + h // 2

        # 在原图上标记亮源位置
        cv2.circle(img, (cX, cY), 10, (0, 255, 0), -1)
# cv2.imshow('gray_image',gray_image)
# cv2.imshow('blurred_image',blurred_image)
cv2.imshow('thresh_image',thresh_image)
cv2.imshow('Detected LEDs',img)
cv2.waitKey(0)
cv2.destroyAllWindows()

#
# while True:
#
#
#
#
#     cv2.imshow('frame',img)
#
#     # 按下'Q'键退出循环
#     if cv2.waitKey(1) == ord('q'):
#         break
#
# # # 释放摄像头
# # cap.release()
# # 关闭窗口
# cv2.destroyWindow()
